import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import manager.ExcelManager;

import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class MainController implements Initializable {
    private ExcelManager excelManager;

    @FXML
    private TextField exportPathText;

    @FXML
    private ListView<String> importFileListView;

    @FXML
    private Button importChooseBtn;

    @FXML
    private Button exportChooseBtn;

    @FXML
    private Button actionBtn;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        excelManager = new ExcelManager();
        initUI();
        excelManager.isCompleteProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                alert("Success", "Success!");
                excelManager.setIsComplete(false);
            } else {
                alert("Failed", "Failed!");
                excelManager.setIsComplete(false);
            }
        });
    }

    private void initUI() {

        importChooseBtn.disableProperty().bindBidirectional(excelManager.isActioningProperty());
        exportChooseBtn.disableProperty().bindBidirectional(excelManager.isActioningProperty());
        actionBtn.disableProperty().bindBidirectional(excelManager.isActioningProperty());
        exportPathText.textProperty().bind(excelManager.exportPathProperty());
        importFileListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        importFileListView.setItems(excelManager.getImportedFilePathList());

        ContextMenu contextMenu = new ContextMenu();
        MenuItem deleteSelectMenuItem = new MenuItem("Delete selected");
        deleteSelectMenuItem.setOnAction((ActionEvent t) -> {
            importFileListView.getSelectionModel().getSelectedItems().forEach(item -> {
                excelManager.removeImportFile(item);
            });
            importFileListView.refresh();
            importFileListView.getSelectionModel().clearSelection();
        });
        MenuItem deleteAllMenuItem = new MenuItem("Delete all");
        deleteAllMenuItem.setOnAction((ActionEvent t) -> {
            excelManager.clearImportFileList();
            importFileListView.refresh();
        });
        contextMenu.getItems().add(deleteSelectMenuItem);
        contextMenu.getItems().add(deleteAllMenuItem);
        importFileListView.setContextMenu(contextMenu);
    }

    public void importChooseClick() {
        List<File> selectedFiles = selectExcelFiles("Choose excel files");

        if (selectedFiles != null && !selectedFiles.isEmpty()) {
            selectedFiles.stream()
                    .map(File::getAbsolutePath)
                    .forEach(fileName -> {
                        excelManager.addImportItem(fileName);
                    });
        }
    }

    public void exportChooseClick() {
        File exportPathFile = selectExportPath("Choose export path");

        if (exportPathFile != null) {
            excelManager.setExportPath(exportPathFile.getAbsolutePath());
        }
    }

    public void startActionClick() {
        if (excelManager.isImportFileListNullOrEmpty()) {
            alert("Notify", "Please choose import files");
            return;
        }

        if (excelManager.isExportFileNullOrEmpty()) {
            alert("Notify", "Please choose export path");
            return;
        }

        excelManager.action(ExcelManager.Mode.toExcel);
    }

    private List<File> selectExcelFiles(String windowName) {
        FileChooser importFilesChooser = new FileChooser();
        importFilesChooser.setTitle(windowName);
        importFilesChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("Excel Files", "*.xlsx", "*.xls")
        );
        return importFilesChooser.showOpenMultipleDialog(null);
    }

    private File selectExportPath(String windowName) {
        DirectoryChooser exportPathChooser = new DirectoryChooser();
        exportPathChooser.setTitle(windowName);
        return exportPathChooser.showDialog(null);
    }

    private void alert(String title, String msg) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.titleProperty().set(title);
        alert.headerTextProperty().set(msg);
        alert.showAndWait();
    }
}
